package com.edu.edu.day9_19_week7_homework.thread;

import android.os.AsyncTask;

import com.edu.edu.day9_19_week7_homework.bean.Food;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 9/19 0019.
 */
public class LoadJsonTask extends AsyncTask<String,Void,List<Food>>{


    //创建接口
    public interface onGetJsonResultListener{
        void onGetJsonResult(List<Food> result);
    }
    private onGetJsonResultListener mListener;

    public  LoadJsonTask(onGetJsonResultListener listener){
        this.mListener = listener;
    }


    @Override
    protected List<Food> doInBackground(String... params) {
        byte[] data = HttpUtil.loadData(params[0]);
        try {
            String json = new String(data);
            JSONArray array = new JSONArray(json);
            List<Food> foods = new ArrayList<>();
            for (int i = 0; i < array.length(); i++) {
                Food food = new Food();
                JSONObject obj = array.getJSONObject(i);
                //外层数据
                String recommend_caption = obj.getString("recommend_caption");
                String recommend_cover_pic = obj.getString("recommend_cover_pic");
                String type = obj.getString("type");
                food.setRecommend_caption(recommend_caption);
                food.setRecommend_cover_pic(recommend_cover_pic);
                food.setType(type);
                if(type.equals("media")){
                    JSONObject object = obj.getJSONObject("media");
                    //media里面的数据
                    String caption = object.getString("caption");
                    String video = object.getString("video");
                    String likes_count = object.getString("likes_count");
                    food.setCaption(caption);
                    food.setVideo(video);
                    food.setLikes_count(likes_count);
                    //用户头像
                    JSONObject objThree = object.getJSONObject("user");
                    String avatar = objThree.getString("avatar");
                    food.setAvatar(avatar);
                }
                foods.add(food);
            }
            return foods;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    //处理回调
    @Override
    protected void onPostExecute(List<Food> result) {
        super.onPostExecute(result);
        if(mListener != null && result != null){
            mListener.onGetJsonResult(result);
        }
    }
}
